<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="要实现限流、熔断等功能，首先要解决的问题是如何实时采集服务(资源)调用信息。例如将某一个接口设置的限流阔值 1W&#x2F;tps，那首先如何判断当前的 TPS 是多少？Alibaba Sentinel 采用滑动窗口来实现实时数据的统计。  温馨提示：如果对源码不太感兴趣，可以先跳到文末，看一下滑动窗口的设计原理图，再决定是否需要阅读源码。  1、滑动窗口核心类图我们先对上述核心类做一个简单的介绍，重点关注">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析 Alibaba sentinel 滑动窗口实现原理(文末附原理图)">
<meta property="og:url" content="https://www.codingw.net/posts/a618bda.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="要实现限流、熔断等功能，首先要解决的问题是如何实时采集服务(资源)调用信息。例如将某一个接口设置的限流阔值 1W&#x2F;tps，那首先如何判断当前的 TPS 是多少？Alibaba Sentinel 采用滑动窗口来实现实时数据的统计。  温馨提示：如果对源码不太感兴趣，可以先跳到文末，看一下滑动窗口的设计原理图，再决定是否需要阅读源码。  1、滑动窗口核心类图我们先对上述核心类做一个简单的介绍，重点关注">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191229144055643.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191229144447580.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191229144957318.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191229145158240.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20191229145357710.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-28T14:41:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:07:54.392Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20191229144055643.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/a618bda.html"/>





  <title>源码分析 Alibaba sentinel 滑动窗口实现原理(文末附原理图) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/a618bda.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析 Alibaba sentinel 滑动窗口实现原理(文末附原理图)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-28T22:41:35+08:00">
                2020-10-28
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/a618bda.html" class="leancloud_visitors" data-flag-title="源码分析 Alibaba sentinel 滑动窗口实现原理(文末附原理图)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>要实现限流、熔断等功能，首先要解决的问题是如何实时采集服务(资源)调用信息。例如将某一个接口设置的限流阔值 1W/tps，那首先如何判断当前的 TPS 是多少？Alibaba Sentinel 采用滑动窗口来实现实时数据的统计。</p>
<blockquote>
<p>温馨提示：如果对源码不太感兴趣，可以先跳到文末，看一下滑动窗口的设计原理图，再决定是否需要阅读源码。</p>
</blockquote>
<h2 id="1、滑动窗口核心类图"><a href="#1、滑动窗口核心类图" class="headerlink" title="1、滑动窗口核心类图"></a>1、滑动窗口核心类图</h2><p><img src="https://img-blog.csdnimg.cn/20191229144055643.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>我们先对上述核心类做一个简单的介绍，重点关注核心类的作用与核心属性（重点需要探究其核心数据结构）。</p>
<ul>
<li>Metric<br>指标收集核心接口，主要定义一个滑动窗口中成功的数量、异常数量、阻塞数量，TPS、响应时间等数据。</li>
<li>ArrayMetric<br>滑动窗口核心实现类。</li>
<li>LeapArray<br>滑动窗口顶层数据结构，包含一个一个的窗口数据。</li>
<li>WindowWrap<br>每一个滑动窗口的包装类，其内部的数据结构用 MetricBucket 表示。</li>
<li>MetricBucket<br>指标桶，例如通过数量、阻塞数量、异常数量、成功数量、响应时间，已通过未来配额（抢占下一个滑动窗口的数量）。</li>
<li>MetricEvent<br>指标类型，例如通过数量、阻塞数量、异常数量、成功数量、响应时间等。</li>
</ul>
<h2 id="2、滑动窗口实现原理"><a href="#2、滑动窗口实现原理" class="headerlink" title="2、滑动窗口实现原理"></a>2、滑动窗口实现原理</h2><h4 id="2-1-ArrayMetric"><a href="#2-1-ArrayMetric" class="headerlink" title="2.1 ArrayMetric"></a>2.1 ArrayMetric</h4><p>滑动窗口的入口类为 ArrayMetric ，我们先来看一下其核心代码。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> LeapArray&lt;MetricBucket&gt; data;   <span class="comment">// @1</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ArrayMetric</span><span class="params">(<span class="keyword">int</span> sampleCount, <span class="keyword">int</span> intervalInMs)</span> </span>&#123;    <span class="comment">// @2</span></span><br><span class="line">    <span class="keyword">this</span>.data = <span class="keyword">new</span> OccupiableBucketLeapArray(sampleCount, intervalInMs);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ArrayMetric</span><span class="params">(<span class="keyword">int</span> sampleCount, <span class="keyword">int</span> intervalInMs, <span class="keyword">boolean</span> enableOccupy)</span> </span>&#123;   <span class="comment">// @3</span></span><br><span class="line">	<span class="keyword">if</span> (enableOccupy) &#123;</span><br><span class="line">		<span class="keyword">this</span>.data = <span class="keyword">new</span> OccupiableBucketLeapArray(sampleCount, intervalInMs);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">this</span>.data = <span class="keyword">new</span> BucketLeapArray(sampleCount, intervalInMs);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：ArrayMetric 类唯一的属性，用来存储各个窗口的数据，这个是接下来我们探究的重点。</p>
<p>代码@2，代码@3  该类提供了两个构造方法，其核心参数为：</p>
<ul>
<li>int intervalInMs<br>表示一个采集的时间间隔，例如1秒，1分钟。</li>
<li>int sampleCount<br>在一个采集间隔中抽样的个数，默认为 2，例如当 intervalInMs = 1000时，抽象两次，则一个采集间隔中会包含两个相等的区间，一个区间就是滑动窗口。</li>
<li>boolean enableOccupy<br>是否允许抢占，即当前时间戳已经达到限制后，是否可以占用下一个时间窗口的容量，这里对应 LeapArray 的两个实现类，如果允许抢占，则为 OccupiableBucketLeapArray，否则为   BucketLeapArray。</li>
</ul>
<blockquote>
<p>注意，LeapArray 的泛型类为 MetricBucket，意思就是指标桶，可以认为一个 MetricBucket 对象可以存储一个抽样时间段内所有的指标，例如一个抽象时间段中通过数量、阻塞数量、异常数量、成功数量、响应时间，其实现的奥秘在 LongAdder 中，本文先不对该类进行详细介绍，后续文章会单独来探究其实现原理。</p>
</blockquote>
<p>这次，我们先不去看子类，反其道而行，先去看看其父类。</p>
<h4 id="2-2-LongAdder"><a href="#2-2-LongAdder" class="headerlink" title="2.2 LongAdder"></a>2.2 LongAdder</h4><h5 id="2-2-1-类图与核心属性"><a href="#2-2-1-类图与核心属性" class="headerlink" title="2.2.1 类图与核心属性"></a>2.2.1 类图与核心属性</h5><p><img src="https://img-blog.csdnimg.cn/20191229144447580.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>LeapArray 的核心属性如下：</p>
<ul>
<li>int windowLengthInMs<br>每一个窗口的时间间隔，单位为毫秒。</li>
<li>int sampleCount<br>抽样个数，就一个统计时间间隔中包含的滑动窗口个数，在 intervalInMs 相同的情况下，sampleCount 越多，抽样的统计数据就越精确，相应的需要的内存也越多。</li>
<li>int intervalInMs<br>一个统计的时间间隔。</li>
<li>AtomicReferenceArray&lt;WindowWrap&lt; T&gt;&gt; array<br>一个统计时间间隔中滑动窗口的数组，从这里也可以看出，一个滑动窗口就是使用的 WindowWrap&lt; MetricBucket &gt; 来表示。</li>
</ul>
<p>上面的各个属性的含义是从其构造函数得出来的，请其看构造函数。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">LeapArray</span><span class="params">(<span class="keyword">int</span> sampleCount, <span class="keyword">int</span> intervalInMs)</span> </span>&#123;</span><br><span class="line">    AssertUtil.isTrue(sampleCount &gt; <span class="number">0</span>, <span class="string">&quot;bucket count is invalid: &quot;</span> + sampleCount);</span><br><span class="line">    AssertUtil.isTrue(intervalInMs &gt; <span class="number">0</span>, <span class="string">&quot;total time interval of the sliding window should be positive&quot;</span>);</span><br><span class="line">    AssertUtil.isTrue(intervalInMs % sampleCount == <span class="number">0</span>, <span class="string">&quot;time span needs to be evenly divided&quot;</span>);</span><br><span class="line">    <span class="keyword">this</span>.windowLengthInMs = intervalInMs / sampleCount;</span><br><span class="line">    <span class="keyword">this</span>.intervalInMs = intervalInMs;</span><br><span class="line">    <span class="keyword">this</span>.sampleCount = sampleCount;</span><br><span class="line">    <span class="keyword">this</span>.array = <span class="keyword">new</span> AtomicReferenceArray&lt;&gt;(sampleCount);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那我们继续来看 LeapArray 中的方法，深入探究滑动窗口的实现细节。</p>
<h5 id="2-2-2-currentWindow-详解"><a href="#2-2-2-currentWindow-详解" class="headerlink" title="2.2.2 currentWindow() 详解"></a>2.2.2 currentWindow() 详解</h5><p>该方法主要是根据当前时间来确定处于哪一个滑动窗口中，即找到上图中的 WindowWrap，该方法内部就是调用其重载方法，参数为系统的当前时间，故我们重点来看一下重载方法的实现。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> WindowWrap&lt;T&gt; <span class="title">currentWindow</span><span class="params">(<span class="keyword">long</span> timeMillis)</span> </span>&#123; </span><br><span class="line">	<span class="keyword">if</span> (timeMillis &lt; <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">int</span> idx = calculateTimeIdx(timeMillis);  <span class="comment">// @1</span></span><br><span class="line">	<span class="keyword">long</span> windowStart = calculateWindowStart(timeMillis); <span class="comment">// @2</span></span><br><span class="line">	<span class="keyword">while</span> (<span class="keyword">true</span>) &#123; <span class="comment">// 死循环查找当前的时间窗口，这里之所有需要循环，是因为可能多个线程都在获取当前时间窗口。</span></span><br><span class="line">		WindowWrap&lt;T&gt; old = array.get(idx);  <span class="comment">// @3</span></span><br><span class="line">       		 <span class="keyword">if</span> (old == <span class="keyword">null</span>) &#123;  <span class="comment">// @4</span></span><br><span class="line">			WindowWrap&lt;T&gt; window = <span class="keyword">new</span> WindowWrap&lt;T&gt;(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));</span><br><span class="line">           		 <span class="keyword">if</span> (array.compareAndSet(idx, <span class="keyword">null</span>, window)) &#123;  <span class="comment">// @5</span></span><br><span class="line">				<span class="keyword">return</span> window;</span><br><span class="line">           		 &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				Thread.yield();</span><br><span class="line">           		 &#125;</span><br><span class="line">       		 &#125; <span class="keyword">else</span> <span class="keyword">if</span> (windowStart == old.windowStart()) &#123; <span class="comment">// @6</span></span><br><span class="line">			<span class="keyword">return</span> old;</span><br><span class="line">       		 &#125; <span class="keyword">else</span> <span class="keyword">if</span> (windowStart &gt; old.windowStart()) &#123;  <span class="comment">// @7</span></span><br><span class="line">			<span class="keyword">if</span> (updateLock.tryLock()) &#123;</span><br><span class="line">               			 <span class="keyword">try</span> &#123;</span><br><span class="line">					<span class="keyword">return</span> resetWindowTo(old, windowStart);</span><br><span class="line">                		&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">					updateLock.unlock();</span><br><span class="line">              			&#125;</span><br><span class="line">           		 &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">				Thread.yield();</span><br><span class="line">            		&#125;</span><br><span class="line">        	&#125; <span class="keyword">else</span> <span class="keyword">if</span> (windowStart &lt; old.windowStart()) &#123; <span class="comment">// @8</span></span><br><span class="line">            		<span class="keyword">return</span> <span class="keyword">new</span> WindowWrap&lt;T&gt;(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));</span><br><span class="line">        	&#125;</span><br><span class="line">    	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：计算当前时间会落在一个采集间隔 ( LeapArray ) 中哪一个时间窗口中，即在 LeapArray 中属性 AtomicReferenceArray &lt;WindowWrap&lt; T&gt;&gt; array 的下标。其实现算法如下：</p>
<ul>
<li>首先用当前时间除以一个时间窗口的时间间隔，得出当前时间是多少个时间窗口的倍数，用 n 表示。</li>
<li>然后我们可以看出从一系列时间窗口，从 0 开始，一起向前滚动 n 隔得到当前时间戳代表的时间窗口的位置。现在我们要定位到这个时间窗口的位置是落在 LeapArray 中数组的下标，而一个 LeapArray 中包含 sampleCount 个元素，要得到其下标，则使用 n % sampleCount 即可。</li>
</ul>
<p>代码@2：计算当前时间戳所在的时间窗口的开始时间，即要计算出 WindowWrap 中 windowStart 的值，其实就是要算出小于当前时间戳，并且是 windowLengthInMs 的整数倍最大的数字，Sentinel 给出是算法为 ( timeMillis - timeMillis % windowLengthInMs )。</p>
<p>代码@3：尝试从 LeapArray 中的 WindowWrap 数组查找指定下标的元素。</p>
<p>代码@4：如果指定下标的元素为空，则需要创建一个 WindowWrap 。 其中 WindowWrap 中的 MetricBucket 是调用其抽象方法 newEmptyBucket (timeMillis)，由不同的子类去实现。</p>
<p>代码@5：这里使用了 CAS 机制来更新 LeapArray 数组中的 元素，因为同一时间戳，可能有多个线程都在获取当前时间窗口对象，但该时间窗口对象还未创建，这里就是避免创建多个，导致统计数据被覆盖，如果用 CAS 更新成功的线程，则返回新建好的 WindowWrap ，CAS 设置不成功的线程继续跑这个流程，然后会进入到代码@6。</p>
<p>代码@6：如果指定索引下的时间窗口对象不为空并判断起始时间相等，则返回。</p>
<p>代码@7：如果原先存在的窗口开始时间小于当前时间戳计算出来的开始时间，则表示 bucket 已被弃用。则需要将开始时间重置到新时间戳对应的开始时间戳，重置的逻辑将在下文详细介绍。</p>
<p>代码@8：应该不会进入到该分支，因为当前时间算出来时间窗口不会比之前的小。</p>
<h5 id="2-2-3-isWindowDeprecated-详解"><a href="#2-2-3-isWindowDeprecated-详解" class="headerlink" title="2.2.3 isWindowDeprecated() 详解"></a>2.2.3 isWindowDeprecated() 详解</h5><p>接下来我们来看一下窗口的过期机制。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isWindowDeprecated</span><span class="params">(<span class="comment">/*@NonNull*/</span> WindowWrap&lt;T&gt; windowWrap)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> isWindowDeprecated(TimeUtil.currentTimeMillis(), windowWrap);</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isWindowDeprecated</span><span class="params">(<span class="keyword">long</span> time, WindowWrap&lt;T&gt; windowWrap)</span> </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> time - windowWrap.windowStart() &gt; intervalInMs;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>判断滑动窗口是否生效的依据是当系统时间与滑动窗口的开始时间戳的间隔大于一个采集时间，即表示过期。即从当前窗口开始，通常包含的有效窗口为 sampleCount 个有效滑动窗口。</p>
<h5 id="2-2-4-getPreviousWindow-详解"><a href="#2-2-4-getPreviousWindow-详解" class="headerlink" title="2.2.4 getPreviousWindow() 详解"></a>2.2.4 getPreviousWindow() 详解</h5><p>根据当前时间获取前一个有效滑动窗口，其代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> WindowWrap&lt;T&gt; <span class="title">getPreviousWindow</span><span class="params">(<span class="keyword">long</span> timeMillis)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (timeMillis &lt; <span class="number">0</span>) &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> idx = calculateTimeIdx(timeMillis - windowLengthInMs); <span class="comment">// @1</span></span><br><span class="line">    timeMillis = timeMillis - windowLengthInMs;</span><br><span class="line">    WindowWrap&lt;T&gt; wrap = array.get(idx);</span><br><span class="line">    <span class="keyword">if</span> (wrap == <span class="keyword">null</span> || isWindowDeprecated(wrap)) &#123;                 <span class="comment">// @2</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">   <span class="keyword">if</span> (wrap.windowStart() + windowLengthInMs &lt; (timeMillis)) &#123;   <span class="comment">// @3</span></span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> wrap;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>其实现的关键点如下：<br>代码@1：用当前时间减去一个时间窗口间隔，然后去定位所在 LeapArray 中 数组的下标。<br>代码@2：如果为空或已过期，则返回 null。<br>代码@3：如果定位的窗口的开始时间再加上 windowLengthInMs 小于 timeMills ，说明失效，则返回 null，通常是不会走到该分支。</p>
<h5 id="2-2-5-滑动窗口图示"><a href="#2-2-5-滑动窗口图示" class="headerlink" title="2.2.5 滑动窗口图示"></a>2.2.5 滑动窗口图示</h5><p>经过上面的分析，虽然还有一个核心方法 (resetWindowTo) 未进行分析，但我们应该可以画出滑动窗口的实现的实现原理图了。<br><img src="https://img-blog.csdnimg.cn/20191229144957318.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>接下来对上面的图进行一个简单的说明：下面的示例以采集间隔为 1 s，抽样次数为 2。</p>
<span id="more"></span>

<p>首先会创建一个 LeapArray，内部持有一个数组，元素为 2,一开始进行采集时，数组的第一个，第二个下标都会 null，例如当前时间经过 calculateTimeIdx 定位到下标为 0，此时没有滑动窗口，会创建一个滑动窗口，然后该滑动窗口会采集指标，随着进入 1s 的后500ms，后会创建第二个抽样窗口。</p>
<p>然后时间前进 1s，又会定位到下标为 0 的地方，但此时不会为空，因为有上一秒的采集数据，故需要将这些采集数据丢弃 ( MetricBucket value )，然后重置该窗口的 windowStart，这就是 resetWindowTo 方法的作用。</p>
<p>在 ArrayMetric 的构造函数出现了 LeapArray 的两个实现类型 BucketLeapArray 与 OccupiableBucketLeapArray。</p>
<p>其中 BucketLeapArray 比较简单，在这里就不深入研究了， 我们接下来将重点探讨一下 OccupiableBucketLeapArray 的实现原理，即支持抢占未来的“令牌”。</p>
<h2 id="3、OccupiableBucketLeapArray-详解"><a href="#3、OccupiableBucketLeapArray-详解" class="headerlink" title="3、OccupiableBucketLeapArray 详解"></a>3、OccupiableBucketLeapArray 详解</h2><p>所谓的 OccupiableBucketLeapArray ，实现的思想是当前抽样统计中的“令牌”已耗尽，即达到用户设定的相关指标的阔值后，可以向下一个时间窗口，即借用未来一个采样区间。接下来我们详细来探讨一下它的核心实现原理。</p>
<p>3.1 类图<br><img src="https://img-blog.csdnimg.cn/20191229145158240.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>我们重点关注一下 OccupiableBucketLeapArray 引入了一个 FutureBucketLeapArray 的成员变量，其命名叫 borrowArray，即为借用的意思。</p>
<h4 id="3-2-构造函数"><a href="#3-2-构造函数" class="headerlink" title="3.2 构造函数"></a>3.2 构造函数</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">OccupiableBucketLeapArray</span><span class="params">(<span class="keyword">int</span> sampleCount, <span class="keyword">int</span> intervalInMs)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">super</span>(sampleCount, intervalInMs);</span><br><span class="line">    <span class="keyword">this</span>.borrowArray = <span class="keyword">new</span> FutureBucketLeapArray(sampleCount, intervalInMs);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>从构造函数可以看出，不仅创建了一个常规的 LeapArray，对应一个采集周期，还会创建一个  borrowArray ，也会包含一个采集周期。</p>
<h4 id="3-3-newEmptyBucket"><a href="#3-3-newEmptyBucket" class="headerlink" title="3.3 newEmptyBucket"></a>3.3 newEmptyBucket</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> MetricBucket <span class="title">newEmptyBucket</span><span class="params">(<span class="keyword">long</span> time)</span> </span>&#123;</span><br><span class="line">	MetricBucket newBucket = <span class="keyword">new</span> MetricBucket();   <span class="comment">// @1</span></span><br><span class="line">	MetricBucket borrowBucket = borrowArray.getWindowValue(time);  <span class="comment">// @2</span></span><br><span class="line">	<span class="keyword">if</span> (borrowBucket != <span class="keyword">null</span>) &#123;  </span><br><span class="line">		newBucket.reset(borrowBucket);  </span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> newBucket;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我们知道 newEmptyBucket 是在获取当前窗口时，对应的数组下标为空的时会创建。<br>代码@1：首先新建一个 MetricBucket。<br>代码@2：在新建的时候，如果曾经有借用过未来的滑动窗口，则将未来的滑动窗口上收集的数据 copy 到新创建的采集指标上，再返回。</p>
<h4 id="3-4-resetWindowTo"><a href="#3-4-resetWindowTo" class="headerlink" title="3.4 resetWindowTo"></a>3.4 resetWindowTo</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> WindowWrap&lt;MetricBucket&gt; <span class="title">resetWindowTo</span><span class="params">(WindowWrap&lt;MetricBucket&gt; w, <span class="keyword">long</span> time)</span> </span>&#123;      </span><br><span class="line">    w.resetTo(time);</span><br><span class="line">    MetricBucket borrowBucket = borrowArray.getWindowValue(time);</span><br><span class="line">    <span class="keyword">if</span> (borrowBucket != <span class="keyword">null</span>) &#123;</span><br><span class="line">        w.value().reset();</span><br><span class="line">        w.value().addPass((<span class="keyword">int</span>)borrowBucket.pass());</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        w.value().reset();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> w;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>遇到过期的滑动窗口时，需要对滑动窗口进行重置，这里的思路和 newEmptyBucket 的核心思想是一样的，即如果存在已借用的情况，在重置后需要加上在未来已使用过的许可，就不一一展开了。</p>
<h4 id="3-5-addWaiting"><a href="#3-5-addWaiting" class="headerlink" title="3.5 addWaiting"></a>3.5 addWaiting</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addWaiting</span><span class="params">(<span class="keyword">long</span> time, <span class="keyword">int</span> acquireCount)</span> </span>&#123;</span><br><span class="line">	WindowWrap&lt;MetricBucket&gt; window = borrowArray.currentWindow(time);</span><br><span class="line">	window.value().add(MetricEvent.PASS, acquireCount);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>经过上面的分析，先做一个大胆的猜测，该方法应该是当前滑动窗口中的“令牌”已使用完成，借用未来的令牌。将在下文给出证明。</p>
<p>滑动窗口的实现原理就介绍到这里了。大家可以按照上面的代码结合下图做一个理解。<br><img src="https://img-blog.csdnimg.cn/20191229145357710.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<blockquote>
<p>思考题，大家可以画一下 OccupiableBucketLeapArray 滑动窗口的图示。</p>
</blockquote>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/80780dfa.html" rel="next" title="KafkaProducer Sender 线程详解（含详细的执行流程图）">
                <i class="fa fa-chevron-left"></i> KafkaProducer Sender 线程详解（含详细的执行流程图）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/497923c7.html" rel="prev" title="全链路压测必备基础组件之线程上下文管理之“三剑客”">
                全链路压测必备基础组件之线程上下文管理之“三剑客” <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E6%A0%B8%E5%BF%83%E7%B1%BB%E5%9B%BE"><span class="nav-number">1.</span> <span class="nav-text">1、滑动窗口核心类图</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-number">2.</span> <span class="nav-text">2、滑动窗口实现原理</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-ArrayMetric"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 ArrayMetric</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-LongAdder"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 LongAdder</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-1-%E7%B1%BB%E5%9B%BE%E4%B8%8E%E6%A0%B8%E5%BF%83%E5%B1%9E%E6%80%A7"><span class="nav-number">2.0.2.1.</span> <span class="nav-text">2.2.1 类图与核心属性</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-2-currentWindow-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.2.</span> <span class="nav-text">2.2.2 currentWindow() 详解</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-3-isWindowDeprecated-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.3.</span> <span class="nav-text">2.2.3 isWindowDeprecated() 详解</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-4-getPreviousWindow-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.2.4.</span> <span class="nav-text">2.2.4 getPreviousWindow() 详解</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#2-2-5-%E6%BB%91%E5%8A%A8%E7%AA%97%E5%8F%A3%E5%9B%BE%E7%A4%BA"><span class="nav-number">2.0.2.5.</span> <span class="nav-text">2.2.5 滑动窗口图示</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81OccupiableBucketLeapArray-%E8%AF%A6%E8%A7%A3"><span class="nav-number">3.</span> <span class="nav-text">3、OccupiableBucketLeapArray 详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-number">3.0.1.</span> <span class="nav-text">3.2 构造函数</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-newEmptyBucket"><span class="nav-number">3.0.2.</span> <span class="nav-text">3.3 newEmptyBucket</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-resetWindowTo"><span class="nav-number">3.0.3.</span> <span class="nav-text">3.4 resetWindowTo</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-5-addWaiting"><span class="nav-number">3.0.4.</span> <span class="nav-text">3.5 addWaiting</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
